package com.aiyige.page.login;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventAgreement;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.model.Country;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.aiyige.page.login.presenter.RegisterPresenter;
import com.aiyige.page.login.view.IRegisterView;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.VerifyCodeManager;
import com.aiyige.utils.widget.VerifyCodeInputView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.aiyige.page.login.SelectCountryPage.COUNTRY_REQUEST_CODE;

@Route(path = ARouterConfig.RegisterPage)
public class RegisterPage extends BaseActivity implements IRegisterView ,ITimerCallBack {
    public static final String TAG = RegisterPage.class.getSimpleName();
    @BindView(R.id.tv_county_name)
    TextView countryName;
    @BindView(R.id.tv_county_number)
    TextView countryNumber;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.iv_agreement)
    ImageView ivAgreement;
    @BindView(R.id.widget_verify_code)
    VerifyCodeInputView widgetVerifyCode;
    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.ll_top)
    LinearLayout llTop;

    boolean isAgreement = true;

    private RegisterPresenter presenter = new RegisterPresenter(this);
    Country selectedCountry;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_register);
        ButterKnife.bind(this);

        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();
            }
        });
        widgetVerifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();
            }
        });
        setAutoRegisterEventBus(true);
        VerifyCodeManager.getInstance().addLoginCallBack(this);
        widgetVerifyCode.setInputAction(new VerifyCodeInputView.Callback() {
            @Override
            public void onNext() {
                if (btnNext.isEnabled()) {
                    btnNext.performClick();
                }
            }
        });

        // 键盘显示隐藏监听
        AppUtils.addOnSoftKeyBoardVisibleListener(this, new AppUtils.SoftKeyBoardCallback() {
            @Override
            public void show() {
                RelativeLayout.LayoutParams ll  = (RelativeLayout.LayoutParams) llTop.getLayoutParams();
                ll.setMargins(0, UIHelper.dip2px(RegisterPage.this,-40), 0, 0);
                llTop.setLayoutParams(ll);
            }

            @Override
            public void hide() {
                RelativeLayout.LayoutParams ll  = (RelativeLayout.LayoutParams) llTop.getLayoutParams();
                ll.setMargins(0, UIHelper.dip2px(RegisterPage.this,0), 0, 0);
                llTop.setLayoutParams(ll);
            }
        });
        btnNext.setEnabled(false);
    }

    private void checkInput() {
        boolean isNull = true;
        if (!isEmpty(getUserName()) && !isEmpty(getVerifyCode())
                && getVerifyCode().length() == 6 && isAgreement) {
            isNull = false;
        }
        btnNext.setEnabled(!isNull);
    }



    @Subscribe
    public void onLoginEvent(EventLogin event) {
        finish();
    }

    @Override
    public String getUserName() {
        return etUsername.getText().toString().trim();
    }

    @Override
    public String getVerifyCode() {
        return widgetVerifyCode.getVerifyCode();
    }

    @Override
    public void setVerifyCode(String verifyCode) {
        widgetVerifyCode.setVerifyCode(verifyCode);
    }

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    public void loginWechat() {
        presenter.loginWeChat(RegisterPage.this);
    }

    @Override
    public void loginQQ() {
        presenter.loginQQ(RegisterPage.this);
    }

    @Override
    public void loginWeibo() {
        presenter.loginWeibo(RegisterPage.this);
    }

    @Override
    public void gotoSelectCounty() {

    }

    @Override
    public void gotoUserAgreement() {

    }

    @Override
    public void gotoCallService() {

    }

    @Override
    public void showError(String errorDetail) {
        ToastX.show(this,errorDetail);
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    @OnClick({R.id.rl_back, R.id.tv_county_name, R.id.tv_county_number, R.id.rl_select_county, R.id.btn_send_verify_code, R.id.btn_next, R.id.ll_agreement,R.id.rl_agreement,R.id.tv_agreement, R.id.iv_login_wechat, R.id.iv_login_qq, R.id.iv_login_blog,R.id.tv_call_service,R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_county_name:
            case R.id.tv_county_number:
            case R.id.rl_select_county:
//                ARouter.getInstance().build(ARouterConfig.SelectCountryPage).navigation(this,COUNTRY_REQUEST_CODE);
                break;
            case R.id.btn_send_verify_code:
                presenter.sendVerifyCode();
                break;
            case R.id.btn_next:
                if (!isAgreement) {
                    ToastX.show(getString(R.string.please_agreement));
                    return;
                }
                presenter.next(RegisterPage.this);
                break;
            case R.id.tv_agreement:
                ARouter.getInstance()
                        .build(ARouterConfig.WebViewPage)
                        .withString("url", BuildConfig.DEBUG ? "http://m.test.dance365.com/agreement.html" :
                                "https://m.dance365.com/agreement.html")
                        .withBoolean("noTitleBar", false)
                        .withBoolean("disableNav", false)
                        .withString("fixedTitle",getString(R.string.china_dance_user_agreement))
                        .navigation();
                break;
            case R.id.tv_call_service:
                Intent intent1=  new Intent(Intent.ACTION_DIAL);
                intent1.setData(Uri.parse("tel:4008081758"));
                startActivity(intent1);
                break;
            case R.id.rl_agreement:
            case R.id.iv_agreement:
                isAgreement = !isAgreement;
                ivAgreement.setImageResource(isAgreement?R.drawable.login_agreed:R.drawable.login_disagree);
                checkInput();
                break;
            case R.id.iv_login_wechat:
                loginWechat();
                break;
            case R.id.iv_login_qq:
                loginQQ();
                break;
            case R.id.iv_login_blog:
                loginWeibo();
                break;
        }
    }

    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        btnSendVerifyCode.setClickable(false);
        btnSendVerifyCode.setText((l / 1000) + "s");
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_gray_b1b5c1));
    }

    @Override
    public void onFinish() {
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_black_111111));
        //重新给Button设置文字
        btnSendVerifyCode.setText(getResources().getString(R.string.get_verification_code));
        //设置可点击
        btnSendVerifyCode.setClickable(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        VerifyCodeManager.getInstance().removeLoginCallBack(this);
    }

    private void setCountry(Country country) {
        this.selectedCountry = country;
        countryName.setText(selectedCountry.getCountryName());
        countryNumber.setText(selectedCountry.getPhoneCode());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (COUNTRY_REQUEST_CODE == requestCode) {
            Country country;
            try {
                country = (Country) data.getSerializableExtra("country");
                setCountry(country);
            } catch (Exception e) {

            }
        }
    }
}
